package com.wl.es7.study.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wl.es7.study.entity.CarES;
import lombok.SneakyThrows;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @SneakyThrows
    @GetMapping("/car")
    public String car(){
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        NativeSearchQuery nativeSearchQuery = builder.withQuery(QueryBuilders.matchAllQuery())
                .withPageable(PageRequest.of(0, 20, Sort.by(Sort.Order.desc("minPrice"))))
                .addAggregation(AggregationBuilders.terms("brand_group").field("brand"))
                .build();

        SearchHits<CarES> searchHits = elasticsearchRestTemplate.search(nativeSearchQuery, CarES.class);
        List<CarES> carES = searchHits.getSearchHits().stream().map(SearchHit::getContent).collect(Collectors.toList());
        Aggregations aggregations = searchHits.getAggregations();
        List<Aggregation> aggregations1 = aggregations.asList();
        System.out.println(objectMapper.writeValueAsString(aggregations1));

        return objectMapper.writeValueAsString(aggregations1);
    }
}
